
const kindeditiorDirective = function($timeout) {
  'ngInject';

  return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
      ngModel: '=',
      keOptions: '=?', // KindEditor 配置选项
      keReadonly: '=?', // 只读模式
      keHeight: '@?', // 编辑器高度
      keWidth: '@?' // 编辑器宽度
    },
    link: function(scope, element, attrs, ngModelCtrl) {
      let editor;
      
      // 默认配置
      const defaultOptions = {
        width: scope.keWidth || '100%',
        height: scope.keHeight || '300px',
        minWidth: '350px',
        minHeight: '200px',
        uploadJson: '/api/upload/image', // 图片上传接口
        fileManagerJson: '/api/upload/files', // 文件管理接口
        allowFileManager: true,
        allowImageUpload: true,
        allowFlashUpload: false,
        allowMediaUpload: false,
        resizeType: 1, // 2或1，1表示可以调整高度
        themeType: 'default',
        langType: 'zh-CN',
        newlineTag: 'br',
        pasteType: 1, // 0:禁止粘贴, 1:纯文本粘贴, 2:HTML粘贴
        dialogAlignType: 'page',
        shadowMode: false,
        zIndex: 999999,
        useContextmenu: true,
        syncType: 'form',
        indentChar: '\t',
        cssPath: '',
        cssData: '',
        bodyClass: 'ke-content',
        colorTable: [
          ['#E53E3E', '#DD6B20', '#D69E2E', '#38A169', '#00B5D8', '#3182CE', '#805AD5', '#D53F8C'],
          ['#FC8181', '#F6AD55', '#F6E05E', '#68D391', '#4FD1C7', '#63B3ED', '#A78BFA', '#F687B3'],
          ['#FED7D7', '#FEEBC8', '#FEFCBF', '#C6F6D5', '#B2F5EA', '#BEE3F8', '#E9D5FF', '#FBB6CE'],
          ['#000000', '#424242', '#636363', '#9C9C94', '#CEC6CE', '#EFEFEF', '#F7F7F7', '#FFFFFF']
        ],
        items: [
          'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
          'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
          'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
          'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
          'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
          'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
          'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
          'anchor', 'link', 'unlink'
        ],
        afterCreate: function() {
          // 编辑器创建完成后的回调
          this.loadPlugin('autoheight');
          updateModelFromEditor();
        },
        afterChange: function() {
          // 内容变化时更新模型
          updateModelFromEditor();
        },
        afterBlur: function() {
          // 失去焦点时更新模型
          updateModelFromEditor();
        }
      };

      // 合并用户配置
      const options = angular.extend({}, defaultOptions, scope.keOptions || {});

      // 如果是只读模式，调整配置
      if (scope.keReadonly) {
        options.items = [];
        options.resizeType = 0;
        options.allowImageUpload = false;
        options.allowFileManager = false;
      }

      // 初始化编辑器
      function initEditor() {
        // 确保 KindEditor 已加载
        if (typeof KindEditor === 'undefined') {
          console.error('KindEditor 未加载，请确保已引入 KindEditor 脚本');
          return;
        }

        $timeout(function() {
          editor = KindEditor.create(element[0], options);
          
          // 设置初始值
          if (ngModelCtrl.$viewValue) {
            editor.html(ngModelCtrl.$viewValue);
          }
        }, 0);
      }

      // 从编辑器更新模型
      function updateModelFromEditor() {
        if (editor) {
          const content = editor.html();
          if (content !== ngModelCtrl.$viewValue) {
            $timeout(function() {
              ngModelCtrl.$setViewValue(content);
            }, 0);
          }
        }
      }

      // 从模型更新编辑器
      function updateEditorFromModel() {
        if (editor && ngModelCtrl.$viewValue !== editor.html()) {
          editor.html(ngModelCtrl.$viewValue || '');
        }
      }

      // 监听模型变化
      ngModelCtrl.$render = function() {
        updateEditorFromModel();
      };

      // 监听只读状态变化
      scope.$watch('keReadonly', function(newVal, oldVal) {
        if (newVal !== oldVal && editor) {
          if (newVal) {
            editor.readonly(true);
          } else {
            editor.readonly(false);
          }
        }
      });

      // 监听配置变化
      scope.$watch('keOptions', function(newVal, oldVal) {
        if (newVal !== oldVal && editor) {
          // 重新初始化编辑器
          editor.remove();
          initEditor();
        }
      }, true);

      // 清理函数
      scope.$on('$destroy', function() {
        if (editor) {
          editor.remove();
          editor = null;
        }
      });

      // 初始化编辑器
      initEditor();
    }
  };
};

// KindEditor 服务，用于全局配置和控制
const kindEditorService = function() {
  'ngInject';

  let globalConfig = {};

  return {
    // 设置全局配置
    setGlobalConfig: function(config) {
      globalConfig = angular.extend(globalConfig, config);
    },

    // 获取全局配置
    getGlobalConfig: function() {
      return angular.copy(globalConfig);
    },

    // 创建编辑器实例
    create: function(element, options) {
      const config = angular.extend({}, globalConfig, options);
      return KindEditor.create(element, config);
    },

    // 销毁所有编辑器实例
    removeAll: function() {
      if (typeof KindEditor !== 'undefined') {
        KindEditor.removeAll();
      }
    },

    // 获取编辑器版本
    getVersion: function() {
      return typeof KindEditor !== 'undefined' ? KindEditor.VERSION : null;
    },

    // 预设配置
    presets: {
      // 简单配置
      simple: {
        items: [
          'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 
          'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 
          'insertunorderedlist', '|', 'link', 'unlink'
        ],
        height: '200px'
      },

      // 完整配置
      full: {
        items: [
          'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
          'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
          'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
          'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
          'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
          'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image',
          'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
          'anchor', 'link', 'unlink'
        ],
        height: '300px'
      },

      // 只读配置
      readonly: {
        items: [],
        resizeType: 0,
        allowImageUpload: false,
        allowFileManager: false
      },

      // 评论配置
      comment: {
        items: [
          'bold', 'italic', 'underline', '|', 'forecolor', '|', 'link', 'unlink', '|', 
          'emoticons', '|', 'removeformat'
        ],
        height: '150px',
        minHeight: '100px'
      }
    }
  };
};

function initKindEditorDirective() {
  const angular = window.angular;
  
  if (!angular) {
    console.error('Angular 未找到，无法初始化KindEditor指令模块');
    return;
  }

  angular.module('app.directives.kindeditor', [])
    .directive('kindeditor', kindeditiorDirective)
    .service('KindEditorService', kindEditorService);
}

// Listen for vendor libs loaded event
window.addEventListener('vendorLibsLoaded', () => {
  initKindEditorDirective();
});

// If Angular already loaded, init directly  
if (window.angular) {
  initKindEditorDirective();
}